<template>
    <div id="chart" ref="chartRef" :style="{ width: '480px', height: '117px' }"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick, type Ref } from 'vue';
import * as echarts from 'echarts';

const chartRef: Ref<HTMLElement | null> = ref(null);
let chartInstance: echarts.ECharts | null = null;

// 监听父组件传入的 scale
const props = defineProps<{
  scale: number;
}>();

// 初始化图表
const initChart = (): void => {
  if (!chartRef.value) return;

  chartInstance = echarts.init(chartRef.value, undefined, {
    devicePixelRatio: window.devicePixelRatio * (props.scale || 1),
  });

  const option: echarts.EChartsOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'line',
      },
    },
    grid: {
      left: '0%',
      top: 20,
      right: '3%',
      bottom: '0%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
      axisLabel: {
        color: '#fff',
        fontSize: 8,
      },
    },
    yAxis: {
      type: 'value',
      name: 'mm',
      nameTextStyle: {
        color: '#fff',
        fontSize: 8,
        padding: [0, 0, 0, 10],
      },
      axisLabel: {
        color: '#fff',
        fontSize: 8,
      },
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: '#444',
          width: 0.3,
          dashOffset: 5,
        },
      },
    },
    series: [
      {
        name: '雨量监测',
        type: 'line',
        smooth: true,
        data: [12, 25, 30, 22, 18, 35, 40, 28, 15, 10, 5, 8],
        itemStyle: {
          color: '#3BB7FF',
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(59, 183, 255, 0.5)' },
            { offset: 0.6, color: 'rgba(59, 183, 255, 0.1)' },
            { offset: 1, color: 'rgba(59, 183, 255, 0)' },
          ]),
        },
        symbol: 'circle',
        symbolSize: 7,
        lineStyle: {
          width: 0.5,
        },
        label: {
          show: true,
          position: 'top',
          color: '#fff',
          fontSize: 8,
          formatter: ({ value }: { value: number }) => value,
          offset: [0, 3],
        },
        emphasis: {
          label: {
            show: false,
          },
        },
      },
    ],
  };

  chartInstance.setOption(option);
};

const resizeChart = (): void => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

// 监听 scale 变化重新渲染图表
watch(
  () => props.scale,
  () => {
    if (chartInstance) {
      nextTick(() => {
        chartInstance?.dispose();
        initChart();
      });
    }
  }
);

onMounted(() => {
  initChart();
  window.addEventListener('resize', resizeChart);
});
</script>
